﻿using Mengsk.ProxyDelivery.App.Service;
using Mengsk.ProxyDelivery.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Mengsk.ProxyDelivery.App.UI.Delivery
{
    /// <summary>
    /// ReturnUserControl.xaml 的交互逻辑
    /// </summary>
    public partial class ReturnUserControl : UserControl, IPlugin
    {
        private bool myLoaded = false;
        private OrderChangeService orderChangeService = ServiceContainer.GetService<OrderChangeService>();

        private System.Collections.ObjectModel.ObservableCollection<OrderChangeViewModel> orderChanges = new System.Collections.ObjectModel.ObservableCollection<OrderChangeViewModel>();

        public string Title
        {
            get { return "退货收件"; }
        }

        public Control UIControl
        {
            get { return this; }
        }

        public ReturnUserControl()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (this.myLoaded)
            {
                return;
            }
            this.myLoaded = true;
            this.cbbDeliveryCompanies.ItemsSource = Domain.DeliveryCompanyHelper.GetDeliveryCompany();
            this.dgvOrderChanges.ItemsSource = this.orderChanges;
            this.orderChanges.CollectionChanged += orderChanges_CollectionChanged;
        }

        void orderChanges_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            this.tbTotalInfo.Text = "当前共:" + this.orderChanges.Select(obj => obj.DeliveryNumber).Distinct().Count() + "条快递记录, 退换货记录:" + this.orderChanges.Where(obj => obj.Source.Id > 0).Count();
        }


        private void tbDeliveryNumber_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key != Key.Enter)
            {
                e.Handled = false;
                return;
            }

            try
            {
                String deliveryNumber = this.tbDeliveryNumber.Text.Trim().ToUpper();
                if (deliveryNumber.Length < 1)
                {
                    return;
                }
                string deliveryCompany = this.cbbDeliveryCompanies.Text.Trim();
                if (string.IsNullOrWhiteSpace(deliveryCompany))
                {
                    throw new Exception("请选择物流公司");
                }

                if (this.orderChanges.FirstOrDefault(obj => obj.Source.ReturnDeliveryCompany == deliveryCompany && obj.Source.ReturnDeliveryNumber == deliveryNumber) != null)
                {
                    Speaker.Speak("已存在");
                    return;
                }

                //先读取发出信息
                var data = ServiceContainer.GetService<OrderService>().GetByDeliveryNumber(deliveryNumber);
                if (data != null && data.Datas.Count > 0)
                {
                    Speaker.Speak("快递单号在发货系统中已经存在");
                    return;
                }

                //生成收到货记录
                var item = this.orderChangeService.GetByAll(0, 0, 0, "", "", "", 1, DateTime.Now.AddDays(-40), DateTime.Now, 0, 0, deliveryNumber, 0, 0);
                if (item == null || item.Datas.Count < 1)
                {
                    OrderChangeViewModel vm = new OrderChangeViewModel
                    {
                        State = "",
                        Source = new ProxyDelivery.Domain.OrderChange(),
                        OrderGoodsInfo = "",
                        DeliveryNumber = deliveryNumber,
                        DeliveryCompany = deliveryCompany,
                        Comment = "",
                        Action = "删除",
                        Image = "",
                    };
                    this.orderChanges.Add(vm);
                    Speaker.Speak("已接受");
                    return;
                }

                foreach (var oc in item.Datas)
                {
                    OrderGoodsService service = ServiceContainer.GetService<OrderGoodsService>();
                    var orderGoods = service.GetById(oc.OrderGoodsId);
                    String image = "";
                    String goodsInfo = "";

                    if (orderGoods == null)
                    {
                        goodsInfo = "未找到指定商品";
                        image = "";
                    }
                    else
                    {
                        goodsInfo = orderGoods.Vendor + " " + orderGoods.Number + " " + orderGoods.Edtion + " " + orderGoods.Color + " " + orderGoods.Size + " " + orderGoods.Count;
                        if (orderGoods.NumberId > 0)
                        {
                            var shoes = ServiceContainer.GetService<ShoesService>().GetById(orderGoods.NumberId);
                            if (shoes != null)
                            {
                                image = shoes.Image;
                            }
                        }
                    }
                    OrderChangeViewModel vm = new OrderChangeViewModel
                      {
                          State = "",
                          Source = oc,
                          OrderGoodsInfo = goodsInfo,
                          DeliveryNumber = deliveryNumber,
                          DeliveryCompany = deliveryCompany,
                          Comment = "",
                          Action = "删除",
                          Image = image,
                      };
                    this.orderChanges.Add(vm);
                    Speaker.Speak("已接受");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                e.Handled = true;
                this.tbDeliveryNumber.Text = "";
            }
        }


        private void btnClear_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("是否清空?", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
            {
                return;
            }
            this.orderChanges.Clear();
        }

        private void btnUpload_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var s = ServiceContainer.GetService<ArriveInDeliveryService>();
                var sc = ServiceContainer.GetService<OrderChangeService>();
                foreach (var item in this.orderChanges)
                {
                    Mengsk.ProxyDelivery.Domain.ArriveInDelivery ad = new ProxyDelivery.Domain.ArriveInDelivery
                    {
                        ArriveReason = ProxyDelivery.Domain.ArriveReason.Exchange,
                        Comment = item.Comment,
                        CreateTime = DateTime.Now,
                        DeliveryCompany = item.DeliveryCompany,
                        DeliveryNumber = item.DeliveryNumber,
                        GoodsInfo = item.OrderGoodsInfo,
                        Operator = "",
                        OrderChangeId = item.Source.Id,
                        OrderGoodsId = item.Source.OrderGoodsId,
                        OrderId = item.Source.OrderId,
                        Id = 0,
                    };
                    s.Insert(ad);
                    //标记收到
                    if (item.Source.Id > 0)
                    {
                        try
                        {
                            sc.MarkRecived(item.Source.Id);
                        }
                        catch (Exception ex)
                        {
                            throw new Exception(ex.Message + ", " + item.Source.Id);
                        }
                    }
                    item.State = "上传成功";
                    App.DoEvents();
                }
                MessageBox.Show("上传成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Delete_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                OrderChangeViewModel order = (e.Source as Hyperlink).DataContext as OrderChangeViewModel;
                if (order == null)
                {
                    return;
                }
                this.orderChanges.Remove(order);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

    }
}
